const Storage = require('../../utils/storage');
const RULES = require('../../utils/rules');
Page({
  data: {
    roomId: '',
    currentGame: 1,
    totalGames: 9,
    playerA: { nickName: 'A', avatarUrl: '', score: 0 },
    playerB: { nickName: 'B', avatarUrl: '', score: 0 },
    history: [],
    redoStack: [],
    mode: '中式九球',
    rules: {},
    scoreAAnim: '',
    scoreBAnim: ''
  },
  onLoad(query) {
    this.setData({ roomId: query.roomId || '', mode: query.mode || '中式九球' });
    const rules = RULES.getRules(this.data.mode);
    this.setData({ rules, totalGames: rules.maxGames });
    // 云开发实时同步
    if (query.roomId) {
      if (!wx.cloud) {
        wx.showToast({ title: '请在微信开发者工具中启用云开发', icon: 'none' });
        return;
      }
      const db = wx.cloud.database();
      this.watcher = db.collection('rooms').doc(query.roomId).watch({
        onChange: snapshot => {
          if (snapshot.docs && snapshot.docs[0]) {
            const doc = snapshot.docs[0];
            this.setData({
              playerA: doc.playerA || this.data.playerA,
              playerB: doc.playerB || this.data.playerB,
              currentGame: doc.currentGame || 1,
              totalGames: doc.totalGames || rules.maxGames
            });
          }
        },
        onError: err => {
          console.error('watch error', err);
        }
      });
    }
  },
  onUnload() {
    if (this.watcher) this.watcher.close();
  },
  onAddScoreA() {
    this._saveHistory();
    if (this.data.roomId && wx.cloud) {
      const db = wx.cloud.database();
      db.collection('rooms').doc(this.data.roomId).update({
        data: { 'playerA.score': this.data.playerA.score + 1 }
      });
    } else {
      this.setData({ 'playerA.score': this.data.playerA.score + 1 });
    }
    this.setData({ scoreAAnim: 'score-anim' });
    setTimeout(() => this.setData({ scoreAAnim: '' }), 300);
    this._checkGameEnd();
  },
  onAddScoreB() {
    this._saveHistory();
    if (this.data.roomId && wx.cloud) {
      const db = wx.cloud.database();
      db.collection('rooms').doc(this.data.roomId).update({
        data: { 'playerB.score': this.data.playerB.score + 1 }
      });
    } else {
      this.setData({ 'playerB.score': this.data.playerB.score + 1 });
    }
    this.setData({ scoreBAnim: 'score-anim' });
    setTimeout(() => this.setData({ scoreBAnim: '' }), 300);
    this._checkGameEnd();
  },
  onSubScoreA() {
    this._saveHistory();
    if (this.data.playerA.score > 0) {
      if (this.data.roomId && wx.cloud) {
        const db = wx.cloud.database();
        db.collection('rooms').doc(this.data.roomId).update({
          data: { 'playerA.score': this.data.playerA.score - 1 }
        });
      } else {
        this.setData({ 'playerA.score': this.data.playerA.score - 1 });
      }
    }
  },
  onSubScoreB() {
    this._saveHistory();
    if (this.data.playerB.score > 0) {
      if (this.data.roomId && wx.cloud) {
        const db = wx.cloud.database();
        db.collection('rooms').doc(this.data.roomId).update({
          data: { 'playerB.score': this.data.playerB.score - 1 }
        });
      } else {
        this.setData({ 'playerB.score': this.data.playerB.score - 1 });
      }
    }
  },
  onUndo() {
    if (this.data.history.length) {
      const prev = this.data.history.pop();
      this.setData({ ...prev });
      this.data.redoStack.push({
        playerA: { ...this.data.playerA },
        playerB: { ...this.data.playerB }
      });
    }
  },
  onRedo() {
    if (this.data.redoStack.length) {
      const next = this.data.redoStack.pop();
      this.setData({ ...next });
    }
  },
  onNextGame() {
    this._saveHistory();
    this.setData({
      currentGame: this.data.currentGame + 1,
      'playerA.score': 0,
      'playerB.score': 0
    });
  },
  _saveHistory() {
    this.data.history.push({
      playerA: { ...this.data.playerA },
      playerB: { ...this.data.playerB }
    });
    this.setData({ redoStack: [] });
  },
  _checkGameEnd() {
    const winner = this.data.rules.winCondition(this.data.playerA.score, this.data.playerB.score);
    if (winner) {
      const historyList = Storage.get('historyList', []);
      const result = {
        date: new Date().toLocaleString(),
        playerA: this.data.playerA.nickName,
        playerB: this.data.playerB.nickName,
        scoreA: this.data.playerA.score,
        scoreB: this.data.playerB.score,
        winner: winner === 'A' ? this.data.playerA.nickName : this.data.playerB.nickName,
        playerA: { ...this.data.playerA },
        playerB: { ...this.data.playerB },
        mode: this.data.mode
      };
      historyList.push(result);
      Storage.set('historyList', historyList);
      wx.redirectTo({ url: `/pages/result/index?idx=${historyList.length - 1}` });
    }
  }
});
